package com.lv.suyiyong.hfr.ui

import android.widget.ImageView
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SizeUtils
import com.lv.common.base.BaseActivity
import com.lv.common.ktx.LoadSrc
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.Constants
import com.lv.common.utils.MyUtils
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.showToast
import com.lv.common.widget.recyclerview.decoration.SpacesItemDecoration
import com.lv.service.bean.ADBean
import com.lv.service.bean.CompanyBean
import com.lv.service.model.ServiceViewModel
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onFailure
import com.lv.service.network.onSuccess
import com.lv.service.room.company.CompanyItemBean
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.adapter.NewCompanyAdapter
import com.lv.suyiyong.hfr.databinding.ActivityNewCompanyOnlineBinding
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import org.koin.androidx.viewmodel.ext.android.viewModel
import kotlin.math.abs

/**
 * 作者： ygx
 * 创建日期：2023/3/28 5:51 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：新店上线
 */
@Route(path = ARoutUtils.NewCompanyOnLineActivity)
class NewCompanyOnLineActivity : BaseActivity<ActivityNewCompanyOnlineBinding>() {
    private var mScrollY: Int = 0
    private var page: Int = 1
    private var pageSize: Int = Constants.pageSize
    private val mBeans = mutableListOf<CompanyItemBean>()
    private val changeScrollHeight = SizeUtils.dp2px(136.0f)
    private var mAdapter: NewCompanyAdapter? = null
    private var mTopView: ImageView? = null
    private val mTitleUrl =
        "https://suyiyong.oss-cn-hangzhou.aliyuncs.com/iOS/projectPic/hfr/new_company_online.png"
    private val serviceViewModel: ServiceViewModel by viewModel()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    override fun getLayoutRes() = R.layout.activity_new_company_online
    override fun initView() {
        super.initView()
        initStatusBar(this, true, false)
        mBinding.apply {
            StatusBarUtil.setHeightAndPadding(this@NewCompanyOnLineActivity, viewStatusbar)
            ivBackPage.setOnClickListener { finish() }
            ivTitlePage.LoadSrc(mTitleUrl)

        }
    }


    override fun initConfig() {
        super.initConfig()
        initAdapter()
        findAllBanner()
        newCompany()
    }

    private fun initAdapter() {
        mAdapter = NewCompanyAdapter(mBeans)
        mBinding.rvContent.adapter = mAdapter
        mBinding.rvContent.addItemDecoration(
            SpacesItemDecoration(SizeUtils.dp2px(10.0f),0, true)
        )
        val headerView = layoutInflater.inflate(
            R.layout.company_online_header, null, false
        )
        mTopView = headerView.findViewById<ImageView>(R.id.iv_img)
        mAdapter?.addHeaderView(headerView)
    }


    override fun initEvents() {
        super.initEvents()
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                page = 1
                newCompany()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                page++
                newCompany()
            }
        })
        mBinding.rvContent.addOnScrollListener(object : OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                mScrollY += dy
                val abss: Int = abs(mScrollY)
                var mAlpha = 0.0f
                if (abss > changeScrollHeight) {
                    mAlpha = (abss - changeScrollHeight) * 1.0f / changeScrollHeight
                    if (mAlpha > 1.0f) {
                        mAlpha = 1.0f
                    }
                    if (mAlpha < 0.0f) {
                        mAlpha = 0.0f
                    }
                }
                mBinding.viewStatusbarBg.alpha = mAlpha

            }
        })

    }

    override fun initData() {
        super.initData()


    }

    private fun findAllBanner() {
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { serviceViewModel.findAllBanner("10") }.await()
            parseFindAllBannerResult(result)
        }
    }

    private fun parseFindAllBannerResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<List<ADBean>> { code, data, message, result ->
                LogUtils.e("aaa")
                val adBean = data?.get(0)
                mTopView?.LoadSrc(adBean?.image)
//                val items = data?.items
//                MyUtils.recyclerviewSetData(
//                    page, pageSize, mBinding.refreshLayout, mBeans, items, mAdapter
//                )
//                if (mBeans.isEmpty()) {
//                    mAdapter?.setEmptyView(getEmptyView(mBinding.rvContent))
//                }
            }
            onBizError<Any> { code, message, data ->
            }
        }
        data.onFailure {

        }
    }

    private fun newCompany() {
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { serviceViewModel.newCompany(page, pageSize) }.await()
            parseNewCompanyResult(result)
        }
    }

    private fun parseNewCompanyResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<CompanyBean> { code, data, message, result ->
                val items = data?.items
                MyUtils.recyclerviewSetData(
                    page, pageSize, mBinding.refreshLayout, mBeans, items, mAdapter
                )
                if (mBeans.isEmpty()) {
                    mAdapter?.setEmptyView(getEmptyView(mBinding.rvContent))
                }
            }
            onBizError<Any> { code, message, data ->
                mBinding.refreshLayout.finishRefresh()
                mBinding.refreshLayout.finishLoadMore()
                showToast(message)
            }
        }
        data.onFailure {
            mBinding.refreshLayout.finishRefresh()
            mBinding.refreshLayout.finishLoadMore()
        }
    }


}